<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="btnController">
        <el-button class="buttons" @click="handleCreate">
          添加
        </el-button>
      </div>
      <div class="formContainer">
        <label class="filterLabel">关键词:</label>
        <el-input v-model="listQuery.keyword" placeholder="请输入关键词" class="filterInput" @keyup.enter.native="handleFilter" />
        <label class="filterLabel">状态:</label>
        <el-select v-model="listQuery.isshow" class="search-select" placeholder="请选择">
          <el-option label="显示" :value="1" />
          <el-option label="隐藏" :value="2" />
        </el-select>
        <el-button class="buttons" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
      </div>
    </div>
    <el-table :key="tableKey" :data="list" style="width: 100%;" :header-cell-style="{background:'#ebebeb',height:'#54px'}" @sort-change="sortChange">
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" align="center" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="链接地址" align="center">
        <template slot-scope="{row}">
          <a class="link-color" :href="row.url" target="_blank" :title="row.title">{{ row.url }}</a>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="150px">
        <template slot-scope="{row}">
          <el-tag>{{ row.isshow_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="删除后不可以恢复，确定删除吗？"
            @onConfirm="handleDelete(row,$index)"
          >
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="链接名称" prop="title">
          <el-input v-model="rows.title" placeholder="请输入链接名称" />
        </el-form-item>
        <el-form-item label="链接类型">
          <el-radio-group v-model="rows.type" @change="typeChange">
            <el-radio :label="1">文字</el-radio>
            <el-radio :label="2">图片</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="rows.type===1" label="链接地址" prop="password">
          <el-input v-model="rows.url" placeholder="链接地址" />
        </el-form-item>
        <el-form-item v-if="rows.type===2" label="图片">
          <Upload v-model="rows.image" />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-radio-group v-model="rows.isshow">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="realname">
          <el-input v-model="rows.sort" type="number" placeholder="排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, del, add, rows, edit } from '@/api/systemLink'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Upload from '@/components/Upload/uploadImg'
import { notifySuccess } from '@/utils/message'

export default {
  name: 'AttachmentIndex',
  components: { Pagination, Upload },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        per_page: 15,
        importance: null,
        keyword: null,
        type: null,
        sort: 'id',
        order: 'desc',
        filter: [],
        op: [],
        isshow: null
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      rows: {
        id: null,
        title: '',
        url: '',
        isshow: 1,
        sort: 100,
        type: 1,
        image: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑数据',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        title: [{ required: true, message: '链接地址不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      var that = this
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        setTimeout(() => {
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 搜索按钮提交
    searchSumit(e) {
      this.listQuery.filter = e.filter
      this.listQuery.op = e.op
      this.listQuery.page = 1
      this.getList()
    },
    // 搜索查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      notifySuccess('', '操作成功')
      row.status = status
    },
    // 排序
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sort = prop
      this.sortByID(order)
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.order = 'ASC'
      } else {
        this.listQuery.order = 'DESC'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: null,
        title: '',
        url: '',
        isshow: 1,
        sort: 100,
        type: 1,
        image: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(this.rows).then(res => {
            this.list.unshift(this.rows)
            this.dialogFormVisible = false
            notifySuccess(res.msg || '添加成功')
          })
        }
      })
    },
    handleUpdate(row) {
      rows(row.id).then(res => {
        this.rows = res.data
        this.rows.image = res.data.image.url
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          edit(tempData.id,
            tempData.title,
            tempData.url,
            tempData.isshow,
            tempData.sort,
            tempData.type,
            tempData.image).then(res => {
            const index = this.list.findIndex(v => v.id === this.rows.id)
            this.list.splice(index, 1, this.rows)
            this.dialogFormVisible = false
            notifySuccess(res.msg || '编辑功')
          })
        }
      })
    },
    // 删除附件
    handleDelete(row, index) {
      del(row.id).then(res => {
        this.list.splice(index, 1)
        notifySuccess(res.msg || '删除成功')
      })
    },
    typeChange(e) {
      console.log(e)
    }
  }
}
</script>
<style scoped>
.link-color{color: #409eff;}
</style>
